package cn.wolfcode.crm.web.controller;

import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IPermissionService;
import cn.wolfcode.crm.util.JsonResult;
import cn.wolfcode.crm.util.PageResult;
import cn.wolfcode.crm.util.PermissionName;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @program: crm
 * @description:
 * @author: Mr.chen
 * @create: 2018-07-07 22:06
 **/
@Controller
@RequestMapping("permission")
public class PermissionController {
    @Autowired
    private IPermissionService service;

    @RequestMapping("")
    @PermissionName("权限主页")
    @RequiresPermissions("permission:index")
    public String index() {
        return "permission/list";
    }

    @RequestMapping("list")
    @ResponseBody
    @RequiresPermissions("permission:list")
    @PermissionName("权限数据")
    public PageResult list(QueryObject qo) {
        PageResult result = service.query(qo);
        return result;
    }


    @RequestMapping("queryPermissions")
    @ResponseBody
    public List<Permission> queryPermissions() {
        return service.list();
    }


    @RequestMapping("queryAll")
    @ResponseBody
    public PageResult queryAll() {
        List<Permission> list = service.list();
        PageResult result = new PageResult();
        result.setTotal(list.size());
        result.setRows(list);
        System.out.println(list.size());
        return result;
    }


    @RequestMapping("reload")
    @ResponseBody
    @RequiresPermissions("permission:reload")
    @PermissionName("加载权限")
    public JsonResult reload() {
        JsonResult result = new JsonResult();
        try {
            service.reload();
        }catch (Exception e){
            e.printStackTrace();
            result = new JsonResult("保存操作失败");
        }
        return result;
    }

    @RequestMapping("delete")
    @ResponseBody
    @RequiresPermissions("permission:delete")
    @PermissionName("权限删除")
    public JsonResult delete(Long id) {
        JsonResult result = new JsonResult();
        try {
            service.delete(id);
        } catch (Exception e) {
            e.printStackTrace();
            result = new JsonResult("操作失败");
        }
        return result;
    }

    @RequestMapping("queryPermissionByRoleId")
    @ResponseBody
    public List<Permission> queryPermissionByRoleId(Long roleId) {
        return service.queryPermissionByRoleId(roleId);
    }
}
